package cn.code.mycloud.module.envir.service.usergrid;

import cn.code.mycloud.framework.common.pojo.PageResult;
import cn.code.mycloud.framework.common.util.collection.CollectionUtils;
import cn.code.mycloud.framework.common.util.object.BeanUtils;
import cn.code.mycloud.module.envir.controller.admin.usergrid.vo.UserGridPageReqVO;
import cn.code.mycloud.module.envir.controller.admin.usergrid.vo.UserGridSaveReqVO;
import cn.code.mycloud.module.envir.dal.dataobject.usergrid.UserGridDO;
import cn.code.mycloud.module.envir.dal.mysql.usergrid.UserGridMapper;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.code.mycloud.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.code.mycloud.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.code.mycloud.module.envir.enums.ErrorCodeConstants.USER_GRID_NOT_EXISTS;

/**
 * 用户和网格关联 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class UserGridServiceImpl implements UserGridService {

    @Resource
    private UserGridMapper userGridMapper;

    @Override
    public Long createUserGrid(UserGridSaveReqVO createReqVO) {
        // 插入
        UserGridDO userGrid = BeanUtils.toBean(createReqVO, UserGridDO.class);
        userGridMapper.insert(userGrid);
        // 返回
        return userGrid.getId();
    }

    @Override
    public void updateUserGrid(UserGridSaveReqVO updateReqVO) {
        // 校验存在
        validateUserGridExists(updateReqVO.getId());
        // 更新
        UserGridDO updateObj = BeanUtils.toBean(updateReqVO, UserGridDO.class);
        userGridMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserGrid(Long id) {
        // 校验存在
        validateUserGridExists(id);
        // 删除
        userGridMapper.deleteById(id);
    }

    private void validateUserGridExists(Long id) {
        if (userGridMapper.selectById(id) == null) {
            throw exception(USER_GRID_NOT_EXISTS);
        }
    }

    @Override
    public UserGridDO getUserGrid(Long id) {
        return userGridMapper.selectById(id);
    }

    @Override
    public PageResult<UserGridDO> getUserGridPage(UserGridPageReqVO pageReqVO) {
        return userGridMapper.selectPage(pageReqVO);
    }

    @Override
    public Set<Long> getGridUserIdListByGridId(Long gridId) {
        List<UserGridDO> userGridDOS = userGridMapper.selectList("grid_id", gridId);
        return userGridDOS.stream().map(UserGridDO::getUserId).collect(Collectors.toSet());
    }

    @Override
    @DSTransactional
    public void assignGridUser(Long gridId, Set<Long> userIds) {
//        // 获得用户ID
        Set<Long> dbUserIds = convertSet(userGridMapper.selectList("grid_id", gridId),
                UserGridDO::getUserId);
        // 计算新增和删除的用户ID
        Set<Long> userIdList = CollUtil.emptyIfNull(userIds);
        Collection<Long> createUserIds = CollUtil.subtract(userIdList, dbUserIds);
        Collection<Long> deleteUserIds = CollUtil.subtract(dbUserIds, userIdList);
        // 执行新增和删除。对于已经授权的网格，不用做任何处理
        if (!CollectionUtil.isEmpty(createUserIds)) {
            userGridMapper.insertBatch(CollectionUtils.convertList(createUserIds, userId -> {
                UserGridDO entity = new UserGridDO();
                entity.setGridId(gridId);
                entity.setUserId(userId);
                return entity;
            }));
        }
        if (!CollectionUtil.isEmpty(deleteUserIds)) {
            userGridMapper.deleteListByGridIdAndUserIds(gridId, deleteUserIds);
        }
    }

}